# @author：zwt
# @last_modified_time:2021/06/18

import pandas as pd
import datetime

import csv


def StayData_dup(df):
    df['locString'] = df.apply(lambda row: str(row.x) + str(row.y), axis=1)
    df['key'] = int(1)
    df.reset_index(drop=True, inplace=True)
    for i in range(1, len(df) - 1):
        if (df.loc[i, 'locString'] == df.loc[i - 1, 'locString']) and (
                df.loc[i, 'locString'] == df.loc[i + 1, 'locString']):
            df.loc[i, 'key'] = 0
    new_df = df[(df['key']) == 1]
    # 只选取需要的列返回(删除为了判定停留新增的列)
    new_df.drop(columns=['locString', 'key'], axis=1, inplace=True)
    new_df.reset_index(drop=True, inplace=True)
    return new_df


# 检测主方法体
def JumpTest(win_df, times_value):
    win_df['front'] = ""
    win_df['next'] = ""
    win_df['all'] = ""
    win_df['key'] = ""
    winRe_df = pd.DataFrame()
    for i in range(len(win_df)-1):
        if i < len(win_df) - 1:
            # 拼接xy坐标
            front_x = win_df.loc[i, 'x']
            front_y = win_df.loc[i, 'y']
            next_x = win_df.loc[i + 1, 'x']
            next_y = win_df.loc[i + 1, 'y']
            # 赋值给新列
            win_df.loc[i, 'front'] = str((front_x, front_y))
            win_df.loc[i, 'next'] = str((next_x, next_y))
            # 首先以前后两个轨迹为组合 判定前后两条数据经纬度的大小 从小到大
            if front_x > next_x:
                win_df.loc[i, 'all'] = win_df.loc[i, 'front'] + '|' + win_df.loc[i, 'next']
            elif front_x < next_x:
                win_df.loc[i, 'all'] = win_df.loc[i, 'next'] + '|' + win_df.loc[i, 'front']
            else:
                if front_y <= next_y:
                    win_df.loc[i, 'all'] = win_df.loc[i, 'front'] + '|' + win_df.loc[i, 'next']
                elif front_y > next_y:
                    win_df.loc[i, 'all'] = win_df.loc[i, 'next'] + '|' + win_df.loc[i, 'front']
    # 将统计重复次数的结果形成dataframe 与原df进行匹配
    res = win_df['all'].value_counts()
    # print(res)
    # 统计重复次数
    # sum_dup = 0
    # for i in range(len(res)):
    #     if res[i] >= times_value:
    #         sum_dup += res[i]
    win_df['key'] = win_df['all'].map(res)
    # print(win_df)
    # 对符合条件的乒乓效应记录输出
    for i in range(len(win_df)):
        if win_df.loc[i, 'key'] >= times_value:
            winRe_df = winRe_df.append(win_df.iloc[i:i + 1, :])
    if len(winRe_df) > 0:
        winRe_df.drop(columns=["front", 'next', 'all', 'key'], axis=1, inplace=True)
    return winRe_df


# 时间窗口的切割
def JumpMain(user_df, time_value, times_value):
    end_time = user_df.loc[len(user_df) - 1, 'time']
    res_df = pd.DataFrame()
    search_df = user_df.copy(deep=True)
    search_df.set_index('time', inplace=True)
    # with open(file_out, 'a+', newline='') as f:
    for i in range(len(user_df)):
        # 获取时间窗口范围
        now_time = user_df.loc[i, 'time']
        next_time = now_time + datetime.timedelta(hours=time_value)
        if next_time > end_time:
            next_time = end_time
        # 获取时间窗口内的数据
        jumpWin_df = (search_df[now_time:next_time]).reset_index()
        # 以window_df（先除去停留）为乒乓效应一个算法的源数据
        window_df = StayData_dup(jumpWin_df)
        # 判断重复跳转正式算法
        if len(window_df) > times_value:
            winRe_df = JumpTest(window_df, times_value)
            res_df = res_df.append(winRe_df)
    res_df = res_df.drop_duplicates(subset=None, keep='first', inplace=False)
    return res_df
